from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from sqlalchemy.orm import Session
import uuid
from typing import List, Optional
import datetime

from ..database import get_db
from ..models import Notice as NoticeModel, User
from ..schemas import Notice as NoticeSchema, NoticeCreate, NoticeUpdate
from ..auth import get_current_active_user
from ..utils.files import save_icon_to_local

router = APIRouter(prefix="/api/chance/notices", tags=["notices"])
# 获取所有通知
@router.get("/", response_model=List[NoticeSchema])
async def get_notices(
    skip: int = 0,
    limit: int = 10,
    title: Optional[str] = None,
    type: Optional[int] = None,
    db: Session = Depends(get_db)
):
    query = db.query(NoticeModel)
    
    if title:
        query = query.filter(NoticeModel.title.contains(title))
    
    if type is not None:
        query = query.filter(NoticeModel.type == type)
    
    notices = query.offset(skip).limit(limit).all()
    return notices

# 创建通知
@router.post("/", response_model=NoticeSchema)
async def create_notice(
    title: str = Form(...),
    pushOrg: str = Form(...),
    pushTime: str = Form(...),  # 前端以字符串形式传递时间
    type: int = Form(...),
    icon: UploadFile = File(None),
    link_url: str = Form(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):  
    # 解析发布时间
    try:
        push_time = datetime.datetime.fromisoformat(pushTime.replace('Z', '+00:00'))
    except ValueError:
        raise HTTPException(status_code=400, detail="发布时间格式错误，请使用ISO格式")
    
    # 验证类型
    if type not in [0, 1, 2]:
        raise HTTPException(status_code=400, detail="通知类型必须是0(系统消息)或1(用户消息)或2(轮播图/广告)")
    
    # 保存图标（如果有）
    icon_path = None
    if icon:
        notice_id = str(uuid.uuid4())
        icon_path = save_icon_to_local(icon, notice_id)
    
    # 创建通知记录
    notice_data = NoticeModel(
        title=title,
        pushOrg=pushOrg,
        pushTime=push_time,
        type=type,
        icon_path=icon_path,
        link_url=link_url,
        creator_id=current_user.id,
        created_at=datetime.datetime.now(),
        updated_at=datetime.datetime.now()
    )
    
    db.add(notice_data)
    db.commit()
    db.refresh(notice_data)
    return notice_data

# 获取单个通知
@router.get("/{notice_id}", response_model=NoticeSchema)
async def get_notice(
    notice_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    notice = db.query(NoticeModel).filter(NoticeModel.id == notice_id).first()
    if not notice:
        raise HTTPException(status_code=404, detail="通知不存在")
    return notice

# 更新通知
@router.put("/{notice_id}", response_model=NoticeSchema)
async def update_notice(
    notice_id: str,
    title: str = Form(None),
    pushOrg: str = Form(None),
    pushTime: str = Form(None),
    type: int = Form(None),
    icon: UploadFile = File(None),
    link_url: str = Form(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    notice = db.query(NoticeModel).filter(NoticeModel.id == notice_id).first()
    if not notice:
        raise HTTPException(status_code=404, detail="通知不存在")
    
    # 更新字段
    update_data = {}
    if title is not None:
        update_data['title'] = title
    if pushOrg is not None:
        update_data['pushOrg'] = pushOrg
    if pushTime is not None:
        try:
            update_data['pushTime'] = datetime.datetime.fromisoformat(pushTime.replace('Z', '+00:00'))
        except ValueError:
            raise HTTPException(status_code=400, detail="发布时间格式错误，请使用ISO格式")
    if type is not None:
        if type not in [0, 1, 2]:
            raise HTTPException(status_code=400, detail="通知类型必须是0(系统消息)或1(用户消息)或2(轮播图/广告)")
        update_data['type'] = type
    
    # 更新图标（如果有）
    if icon:
        icon_id = str(uuid.uuid4())
        icon_path = save_icon_to_local(icon, icon_id)
        update_data['icon_path'] = icon_path
    
    # 更新URL链(如果有)
    if link_url:
        update_data['link_url'] = link_url
    
    # 应用更新
    for key, value in update_data.items():
        setattr(notice, key, value)
    
    notice.updated_at = datetime.datetime.now()
    
    db.commit()
    db.refresh(notice)
    
    return notice